/**
 * @description 验证策略文件
 */
import { Injectable } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { JWT_CONSTANTS } from '../common/constanst';

export interface JwtPayload {
  username: string;
}

@Injectable()
// 验证请求头中的token
export default class JwtAuthStrategy extends PassportStrategy(Strategy, 'jwt') {
  constructor() {
    super({
      // JWT提取方式
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      // 验证token是否过期
      ignoreExpiration: false,
      // 密钥
      secretOrKey: JWT_CONSTANTS.secret,
    });
  }

  /**
   * @description 解析token中的用户名并返回
   * @param payload 解析token
   * @returns username
   */
  async validate(payload: JwtPayload) {
    console.log(payload.username);
    const { username } = payload;
    return {
      username,
    };
  }
}
